<template>
  <a-modal
    v-model:visible="visible"
    width="460px"
    centered
    destroy-on-close
    :closable="false"
    :mask-closable="false"
  >
    <div class="form-header" slot="title">
      <exclamation-circle-outlined class="form-header-icon" />
      <span class="form-header-info">请您输入验证码</span>
    </div>
    <a-form ref="formRef" class="validate-form" :model="form" :rules="rules">
      <a-form-item label="验证码" name="captcha">
        <ul class="form-captcha">
          <li>
            <captcha ref="captRef" :scene="scene" />
            <span class="tip form-captcha-info">输入上图中的字符，不区分大小写</span>
          </li>
          <li>
            <a-input v-model:value="form.captcha" placeholder="验证码">
              <template slot="prefix">
                <safety-outlined class="pre-icon" />
              </template>
            </a-input>
          </li>
        </ul>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button type="primary" size="small" :loading="loading" @click="handleSubmit">
        确定
      </a-button>
      <a-button size="small" @click.stop="close">取消</a-button>
    </template>
  </a-modal>
</template>
<script>
import { defineComponent, ref, reactive } from 'vue'
import Captcha from './captcha.vue'

export default defineComponent({
  components: { Captcha },
  props: {
    modelVisible: {
      type: Boolean,
      default: false
    },
    scene: {
      type: String
    },
    loading: {
      type: Boolean
    }
  },
  emits: ['update:visible', 'on-ok'],
  setup (props, { emit }) {
    const { modelVisible } = props
    const formRef = ref()
    const form = reactive({ captcha: '' })
    const rules = ref({
      captcha: [{
        required: true,
        min: 4,
        max: 4,
        pattern: '[0-9a-zA-Z]{4}',
        message: '请正确输入验证码'
      }]
    })

    const close = () => {
      emit('update:visible', false)
      form.captcha = ''
    }

    const handleSubmit = () => {
      formRef.value.validate().then(() => {
        emit('on-ok', form.captcha)
        close()
      })
    }

    return {
      visible: modelVisible,
      formRef,
      form,
      rules,
      close,
      handleSubmit,
    }
  }
})
</script>
<style lang="less" scoped>
.validate-form {
  padding: 12px 20px 20px;
  font-size: 12px;
}
.form-header {
  padding: 0 10px;
  height: 40px;
  display: flex;
  align-items: center;
  &-icon {
    color: #faad14;
    font-size: 20px;
    display: inline-block;
    vertical-align: middle;
    margin-right: 12px;
  }
  &-info {
    font-size: 14px;
    font-weight: 600;
    color: #454545;
  }
}
.form-captcha {
  li {
    margin-bottom: 8px;
  }
  &-info {
    line-height: 28px;
  }
}
</style>
